import 'dart:convert';

import 'package:http/http.dart' as http;

class API {
  //8.130.20.181
  final String HOST =  "http://192.168.31.254:8080/api";
  // final String HOST =  "http://8.130.20.181:8080/api";

  static String? token ;

  static final DEFAULT_HEADERS = {
    "Access-Control-Allow-Origin":"*",
    "Access-Control-Allow-Methods":"PUT,POST,GET,DELETE",
  };

  Future<dynamic> sendGETRequest(String url) async {
    var response = await http.get(Uri.parse("${HOST}${url}"),headers: {"Cookie":token.toString()});
    return response.body;
  }

  Future<dynamic> sendPostRequest(String url,Map<String,dynamic> params) async {
    http.Response response;
    if(token == null) {
      response = await http.post(Uri.parse("${HOST}${url}"), body: params);
    } else {
      response = await http.post(Uri.parse("${HOST}${url}"),
          headers: {"Cookie": token.toString()},
          body: params);
    }

    if(response.statusCode != 200) {
      return null;
    }
    return response.body;
  }

  Future<dynamic> sendJSONPostRequest(String url,Map<String,dynamic> params) async {
    http.Response response;
    if(token == null) {
       response = await http.post(Uri.parse("${HOST}${url}"),
          body: json.encode(params),
       headers: {"Content-Type":'application/json'});
    } else {
      response = await http.post(Uri.parse("${HOST}${url}"),
          body: json.encode(params),
          headers: {"Cookie":token!,"Content-Type":"application/json"});
    }
    var cookie = response.headers['Cookie'] ?? response.headers['cookie'] ?? response.headers['set-cookie'];

    if(cookie == null) {
      if(response.statusCode == 200) {
        return response.body;
      } else {
        return null;
      }
    }


    RegExp regExp = RegExp(r"JSESSIONID=\w+;");
    RegExp regExp2 = RegExp(r"token=(\w+\-*)*;");
    String sessionId = regExp.allMatches(cookie!).first.group(0)!;
    String tokenString = regExp2.allMatches(cookie).first.group(0)!;
    token = '$sessionId$tokenString';
    if(response.statusCode != 200) {
      return null;
    }
    return response.body;
  }

}
